package ca.etsmtl.log430.lab3;

import java.io.PipedReader;
import java.io.PipedWriter;

public class SplitFilter extends Thread {

	boolean done;
	
	PipedReader inputPipe = new PipedReader();
	
	PipedWriter[] outputPipes;
	
	public SplitFilter(PipedWriter inputPipe, PipedWriter[] outputPipes) {
		try {
			this.inputPipe.connect(inputPipe);
			System.out.println("SplitFilter:: connected to upstream filter.");
		}
		catch (Exception error) {
			System.out.println("SplitFilter:: error connecting input pipe.");
		}
		
		try {
			this.outputPipes = outputPipes;
			System.out.println("SplitFilter:: connected to downstream filters.");
		} catch (Exception Error) {
			System.out.println("SplitFilter:: error connecting output pipes.");
		}
	}
	
	// This is the method that is called when the thread is started
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		// char array is required to turn char into a string
		String lineOfText = "";
		// string is required to look for the keyword
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line
						
						System.out.println("SplitFilter:: received: "
									+ lineOfText + ".");

						System.out.println("SplitFilter:: sending: "
									+ lineOfText + " to output pipes.");
						lineOfText += new String(characterValue);
						
						for (PipedWriter outputPipe : outputPipes) {
							
							outputPipe.write(lineOfText, 0, lineOfText.length());
							outputPipe.flush();
						}

						lineOfText = "";

					} else {

						lineOfText += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

			System.out.println("SplitFilter:: interrupted.");

		} // try/catch

		try {

			inputPipe.close();
			System.out.println("SplitFilter:: input pipe closed.");

			for (PipedWriter outputPipe : outputPipes) {
				outputPipe.close();
			}
			System.out.println("SplitFilter:: output pipes closed.");

		} catch (Exception error) {

			System.out.println("SplitFilter:: error closing pipes.");

		} // try/catch

	} // run
}
